﻿using EasyIot.Common;
using DotNetty.Buffers;
using DotNetty.Common.Utilities;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using System;
using DotNetty.Transport.Channels.Sockets;
using System.Net;
using DotNettyExtensions.entity;

namespace DotNettyExtensions
{
    public class UDPHandler : SimpleChannelInboundHandler<DatagramPacket>
    {
        IProtocolHandler protocol;

        public UDPHandler(IProtocolHandler protocol)
        {
            this.protocol = protocol;
        }

        protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet)
        { 
            var remote = packet.Sender;

            ServerMgr.AddClient(ctx, System.Net.Sockets.ProtocolType.Udp, remote); 

            protocol.ChannelRead(ctx, remote, packet.Content);
        }

        public override void ChannelReadComplete(IChannelHandlerContext ctx)
        {
            ctx.Flush();
        }

        public override void ChannelInactive(IChannelHandlerContext ctx)
        {
            ServerMgr.RemoveClient(ctx, "ChannelInactive");
        }

        public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception)
        {
            ServerMgr.RemoveClient(ctx, "exceptionCaught");
        }

        public override void UserEventTriggered(IChannelHandlerContext ctx, object evt)
        {
            if (evt is IdleStateEvent)
            {
                string type = "未知";
                IdleStateEvent event1 = (IdleStateEvent)evt;
                switch (event1.State)
                {
                    case IdleState.ReaderIdle: type = "read idle"; break;
                    case IdleState.WriterIdle: type = "write idle"; break;
                    case IdleState.AllIdle: type = "all idle"; break;
                    default: break;
                } 
                ServerMgr.RemoveClient(ctx, "超时退出(" + type + ")");
            }
            else
            {
                base.UserEventTriggered(ctx, evt);
            }
        }


        
    }
}